package com.example.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.seckill.pojo.Order;
import com.example.seckill.pojo.SeckillMessage;
import com.example.seckill.pojo.SeckillOrder;
import com.example.seckill.pojo.User;
import com.example.seckill.rabbitmq.MQSender;
import com.example.seckill.service.IGoodsService;
import com.example.seckill.service.IOrderService;
import com.example.seckill.service.ISeckillOrderService;
import com.example.seckill.utils.JsonUtil;
import com.example.seckill.vo.GoodsVo;
import com.example.seckill.vo.RespBean;
import com.example.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: seckill
 * @description: 秒杀接口
 * @author: KingCrimson
 * @create: 2022-08-09 22:40
 **/

@RequestMapping("seckill")
@Controller
public class SecKillController implements InitializingBean {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MQSender mqSender;

    private Map<Long,Boolean> EmptyStockMap = new HashMap<>();


    //windows优化前QPS:435
    //linux优化前QPS:173
    @RequestMapping( "doSeckill2")
    public String doSeckill2(Model model, User user,Long goodsId){
//        System.out.println(goodsId);
        if (null == user){
            return "login";
        }
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1){
            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK);
            return "secKillFail";
        }
        //判断该用户是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId())
                .eq("goods_id", goodsId));
        if (null != seckillOrder){
            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR);
            return "secKillFail";
        }
        //都没有,则下订单
        Order order = orderService.seckill(user,goodsVo);
        model.addAttribute("order",order);
        model.addAttribute("goods",goodsVo);
        return "orderDetail";
    }

    //windows优化前QPS:435
    //    添加缓存后QPS:
    @RequestMapping(value ="doSeckill3",method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSeckill3(Model model, User user, Long goodsId){
//        System.out.println(goodsId);
        if (null == user){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1){
//            model.addAttribute("errmsg", RespBeanEnum.EMPTY_STOCK);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //判断该用户是否重复抢购
//        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId())
//                .eq("goods_id", goodsId));
        SeckillOrder seckillOrder = ((SeckillOrder) redisTemplate.opsForValue().get("user:" + user.getId() + ":" + goodsId));
        if (null != seckillOrder){
//            model.addAttribute("errmsg",RespBeanEnum.REPEATE_ERROR);
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //都没有,则下订单
        Order order = orderService.seckill(user,goodsVo);
        return RespBean.success(order);
    }

    //windows优化前QPS:435
    //    添加缓存后QPS:
    @RequestMapping(value ="doSeckill",method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSeckill( User user, Long goodsId){
//        System.out.println(goodsId);
        if (null == user){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //判断是否重复抢购
        SeckillOrder seckillOrder = ((SeckillOrder) redisTemplate.opsForValue().get("user:" + user.getId() + ":" + goodsId));
        if (null != seckillOrder){
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //内存标记，减少redis访问
        if (EmptyStockMap.get(goodsId)){
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //预减库存
        Long decrement = valueOperations.decrement("seckillGoods:" + goodsId);
        if (decrement < 0){
            EmptyStockMap.put(goodsId,true);
            //小于0，库存清空了
            valueOperations.increment("seckillGoods:" + goodsId);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //下单
        SeckillMessage message = new SeckillMessage(user,goodsId);
        mqSender.sendSeckillMessage(JsonUtil.object2JsonStr(message));
        return RespBean.success(0);
    }


    /**
    * @Description: 获取秒杀结果
    * @Param: 
    * @return: 
    * @Author: KingCrimson
    * @Date: 2022/8/19
    */
    @RequestMapping("/getResult")
    @ResponseBody
    public RespBean result(User user,Long goodsId){
        System.out.println("getResult接收到goodsId:"+goodsId);
        if (null == user){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        Long orderId = seckillOrderService.getResult(user,goodsId);
        return RespBean.success(orderId);
    }


    /**
    * @Description: 系统初始化时的操作，可以把库存加载到redis中
    * @Param: 
    * @return: 
    * @Author: KingCrimson
    * @Date: 2022/8/18
    */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = goodsService.findGoodsVo();
        if (CollectionUtils.isEmpty(list)){
            //如果列表为空,则直接返回
            return;
        }
        list.forEach(goodsVo -> {
            redisTemplate.opsForValue().set("seckillGoods:"+goodsVo.getId(),goodsVo.getStockCount());
            EmptyStockMap.put(goodsVo.getId(), false);
        });
    }
}
